<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
      <el-button
        type="primary"
        plain
        :class="{ 'active': selectedStatus === '' }"
        @click="handleQueryButton('')"
      >
        全部
      </el-button>
      <el-button
        v-for="(item, index) in statusList"
        :key="index"
        type="primary"
        plain
        :class="{ 'active': selectedStatus === item.name }"
        @click="handleQueryButton(item.name)"
      >
        {{ item.name }} {{ item.num }}
      </el-button>
  </ContentWrap>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="企业名称" prop="enterpriseName">
        <el-input
          v-model="queryParams.enterpriseName"
          placeholder="请输入企业名称"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="需求名称" prop="demandName">
        <el-input
          v-model="queryParams.demandName"
          placeholder="请输入需求名称"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>

      <el-form-item label="创建时间" prop="createTime">
        <el-date-picker
          v-model="queryParams.createTime"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-220px"
        />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
        
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true">
      <el-table-column label="序号" align="center" width="80px">
      <template #default="scope">
        {{ serialNumbers[scope.$index] }}
      </template>
    </el-table-column>
      <el-table-column
        label="发布时间"
        align="center"
        prop="createTime"
        :formatter="dateFormatter"
        width="180px"
      />
      <el-table-column label="需求编码" align="center" prop="demandCode" />
      <el-table-column label="企业名称" align="center" prop="enterpriseName" />
      <el-table-column label="需求名称" align="center" prop="demandName" />
      <el-table-column label="需求描述" align="center" prop="demandDescription" />
      <el-table-column label="状态" align="center" prop="status">
        <template #default="scope">
        <span :class="getStatusColorClass(scope.row.status)">
          {{ scope.row.status }}
        </span>
      </template>
      </el-table-column>

      <el-table-column label="操作" align="center" min-width="120px">
        <template #default="scope">

          <!-- <el-button
            link
            type="success"
            @click="openForm('update', scope.row.id, scope.row)"
            v-if="scope.row.status === '已确认'"
          >
          已确认
          </el-button> -->
          <el-button
            link
            type="primary"
            @click="openForm('update', scope.row.id, scope.row)"
            v-if="scope.row.status === '待确认'"
          >
            审核
          </el-button>
          <el-button
            link
            type="primary"
            @click="openForm('update', scope.row.id, scope.row)"
            v-if="scope.row.status === '已确认'"
          >
            编辑
          </el-button>
          <el-button
            link
            type="success"
            @click="openForm('update', scope.row.id, scope.row)"
            v-if="scope.row.status !== '待确认'&& scope.row.status!== '已确认'"
          >
            详情
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <!--<DemandInfoMainForm ref="formRef" @success="getList" :order-status="orderStatus" />-->
</template>
<script setup lang="ts">
import { dateFormatter } from '@/utils/formatTime'
import download from '@/utils/download'
import { DemandInfoMainApi, DemandInfoMainVO,NameNumVo } from '@/api/dd/demandinfomain'
import DemandInfoMainForm from './DemandInfoMainForm.vue'
import {ref} from 'vue'

/** 需求信息主 列表 */
defineOptions({ name: 'DemandInfoMain' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

// const orderStatus: string = ref('待确认')

const loading = ref(true) // 列表的加载中
const list = ref<DemandInfoMainVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  demandCode: undefined,
  enterpriseId: undefined,
  enterpriseName: undefined,
  demandName: undefined,
  demandDescription: undefined,
  status: undefined,
  notPassing: undefined,
  createTime: [],
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中
const statusList = ref<NameNumVo[]>([])


const serialNumbers = ref<number[]>([])

// 记录当前选中的状态
const selectedStatus = ref('');

/** 查询列表 */
const getList = async () => {
  loading.value = true;
 
  try {
    const data = await DemandInfoMainApi.getDemandInfoMainPage(queryParams);
    list.value = data.list;
    total.value = data.total;
    // 生成序号数组
    generateSerialNumbers()
  } finally {
    loading.value = false;
  }
};

/** 查询类型统计 */
const getDemandStatus = async () => {
  loading.value = true;
  try {
    const data = await DemandInfoMainApi.getDemandStatus();
    statusList.value = data;
  
    const waitConfirm = statusList.value.find(item => item.name === '待确认');
  
    if(waitConfirm && waitConfirm.num > 0){
      queryParams.status = '待确认'; 
      selectedStatus.value = '待确认'; // 初始化选中状态
      getList();
    }
    getList();
  } finally {
    loading.value = false;
  }
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1;
  getList();
};

const handleQueryButton = (name) => {
  selectedStatus.value = name; // 更新选中状态
  queryParams.status = name;
  queryParams.pageNo = 1;
  getList();
};



/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

const router = useRouter()
/** 添加/修改操作 */
// const formRef = ref()
// const mainId = ref()
const openForm = (type: string, id?: number, row?: any) => {
  // formRef.value.open(type, id)
  // orderStatus.value = row.status
  // mainId.value = row.id
  router.push({
    name: 'DialogDemandInfoMainForm',
    query: {
      type,
      id,
      mainId: row.id,
      status: row.status
    }
  })
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await DemandInfoMainApi.deleteDemandInfoMain(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await DemandInfoMainApi.exportDemandInfoMain(queryParams)
    download.excel(data, '需求信息主.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}
const getStatusColorClass = (status) => {
  switch (status) {
    case '已确认':
      return 'is-blue';
    case '待确认':
      return 'is-pink';
    case '已完成':
      return 'is-green';
    case '未审核通过':
      return 'is-red';
    case '已关闭':
      return 'is-red';
    default:
      return '';
  }
};

// 生成序号数组
const generateSerialNumbers = () => {
  const startIndex = (queryParams.pageNo - 1) * queryParams.pageSize + 1
  serialNumbers.value = list.value.map((_, index) => startIndex + index)
}

// 监听分页参数变化，重新生成序号
watch([() => queryParams.pageNo, () => queryParams.pageSize], () => {
  generateSerialNumbers()
})
/** 初始化 **/
onMounted(() => {
  getDemandStatus()
  //判断statusList中待确认大于0的话，就把status设置为待确认
  
  getList()
  
})


</script>

<style scoped>
.is-blue {
  color: #409eff;
}
.is-pink {
  color: #ff69b4;
}
.is-green {
  color: #67c23a;
}
.is-red {
  color: #f56c6c;
}
/* 选中状态的样式 */
.active {
  background-color: #409eff;
  color: white;
}
</style>
